package com.avic.rong.questionOrAnswer.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;

import com.avic.rong.BaseFragment;
import com.avic.rong.R;
import com.avic.rong.questionOrAnswer.activity.PersonalHomeActivity;
import com.avic.rong.questionOrAnswer.adapter.QuestionOrAnswerListAdapter;
import com.avic.rong.questionOrAnswer.api.QaaListApi;
import com.avic.rong.questionOrAnswer.api.QaaMyListApi;
import com.avic.rong.questionOrAnswer.bean.QaaMyListBean;
import com.avic.rong.userOrder.event.InformUpdate;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.Unbinder;



/**
 * A simple {@link Fragment} subclass.
 */
public class QuestionOrAnswerFragment extends BaseFragment{


    @BindView(R.id.recy_list)
    RecyclerView recyList;
    @BindView(R.id.loading_layout)
    LoadingLayout loading_layout;
    Unbinder unbinder;

    Unbinder unbinder1;
    private List<QaaMyListBean> listData = new ArrayList<>();
    private QuestionOrAnswerListAdapter questionOrAnswerListAdapter;
    private String homeUserID;

    @Override
    protected void initView() {

        Bundle arguments = getArguments();
        homeUserID = arguments.getString("homeUserID");

        EventBus.getDefault().register(this);
        loading_layout.setStatus(LoadingLayout.LOADING);

        recyList.setLayoutManager(new LinearLayoutManager(getContext()));
        questionOrAnswerListAdapter = new QuestionOrAnswerListAdapter(getContext(), listData);
        recyList.setAdapter(questionOrAnswerListAdapter);

        initData();
    }
    private void initData() {

            Map<String, String> map = new HashMap<>();
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            map.put("token", getSharedPreferencesUtil().getLogintoken());
        }else {
            map.put("token", "");
        }

            map.put("pageNo",currentPageNumber+"" );
            map.put("pageSize", "20");
            map.put("title", "");
            if (TextUtils.isEmpty(homeUserID)) {
                map.put("userId", "");
                final QaaMyListApi qaaMyListApi = new QaaMyListApi((PersonalHomeActivity) getContext(), simpleOnNextListener);
                qaaMyListApi.setCache(false);
                qaaMyListApi.setMap(map);
                HttpManager.getInstance().doHttpDeal(qaaMyListApi);
            } else {
                map.put("userId", homeUserID);
                final QaaListApi qaaListApi = new QaaListApi((PersonalHomeActivity) getContext(), simpleOnNextListener);
                qaaListApi.setCache(false);
                qaaListApi.setMap(map);
                HttpManager.getInstance().doHttpDeal(qaaListApi);
            }

/*
            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(qaaMyListApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    getActivity().onBackPressed();
                }
            });*/

       /* } else {
            loading_layout.setStatus(LoadingLayout.EMPTY);
        }*/
    }

    @Override
    protected void addListener() {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_question_or_answer;
    }

    //融融号主页-用户本人问答列表
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (isRefresh){
                listData.clear();
            }
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ToastTools.showToast(getContext(), subjects.getMsg());
                return;
            }
            if (isRefresh){
                ((PersonalHomeActivity)getContext()).refreshLayout.finishRefresh();
            }else{
                ((PersonalHomeActivity)getContext()).refreshLayout.finishLoadMore();
            }
            loading_layout.setStatus(LoadingLayout.SUCCESS);
            List<QaaMyListBean> data = (List<QaaMyListBean>) subjects.getData();
            listData.addAll(data);
            if (listData!=null&&listData.size()<=0){
                loading_layout.setStatus(LoadingLayout.EMPTY);
            }
            questionOrAnswerListAdapter.notifyDataSetChanged();
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            if (isRefresh){
                ((PersonalHomeActivity)getContext()).refreshLayout.finishRefresh();
            }else{
                ((PersonalHomeActivity)getContext()).refreshLayout.finishLoadMore();
            }
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    @Subscribe
    public void onEventShowThread(InformUpdate event) {
        if (event != null) {
            if (event.getEventType() == InformUpdate.DELETE_QUESTION_INFORM) {
                initData();
            } else if (event.getEventType() == InformUpdate.DELETE_ANSWER_INFORM) {
                initData();
            }

        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }



    public void onLoadMore() {
        isRefresh = false;
        currentPageNumber = currentPageNumber + 1;
        initData();
    }

    public void onRefresh() {
        isRefresh = true;
        currentPageNumber = 1;
        initData();
    }
}
